package com.liu.nb.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.nb.entity.SysRole;
import com.liu.nb.entity.SysUser;
import com.liu.nb.entity.SysUserRole;
import com.liu.nb.service.impl.SysUserService;
import com.liu.nb.util.Const;
import com.liu.nb.util.Result;
import com.liu.nb.util.dto.PasswordDto;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuziyi
 * @since 2021-08-05
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController{
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id){
        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser,"找不到该用户");
        List<SysRole> sysRoles = sysRoleService.listRolesByUserId(id);
        sysUser.setSysRoles(sysRoles);
        return Result.success(sysUser);
    }

    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @RequestMapping("/list")
    public Result list(String username){
        Page<SysUser> page = sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username));
//        把page的记录进行循环
        page.getRecords().forEach(u ->{
//            根据userid,查出来role,并添加到user里边
            u.setSysRoles(sysRoleService.listRolesByUserId(u.getId()));
        });
        return Result.success(page);
    }

    @PreAuthorize("hasAnyAuthority('sys:user:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysUser sysUser){
//        创建时间
        sysUser.setCreated(LocalDateTime.now());
//        默认密码
        String password = bCryptPasswordEncoder.encode(Const.DEFAULT_PASSWORD);
        sysUser.setPassword(password);
//        默认头像
        sysUser.setAvatar(Const.DEFAULT_AVATAR);

        boolean save = sysUserService.save(sysUser);
        return Result.success(save);
    }
    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysUser sysUser,Principal principal){
        SysUser currentUser = sysUserService.getByUsername(principal.getName());
        boolean flag = currentUser.getId()==sysUser.getId();
        Assert.isTrue(!flag,"只能在个人中心内修改自己的信息");

        sysUser.setUpdated(LocalDateTime.now());
        boolean b = sysUserService.updateById(sysUser);
        return Result.success(b);
    }

    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @Transactional
    @PostMapping("/delete")
    public Result delete(@RequestBody Long[] ids,Principal principal){
//        删除该用户
        boolean b = sysUserService.removeByIds(Arrays.asList(ids));
//        删除该用户的中间表信息
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id",ids));
        return Result.success(b);
    }

    @PreAuthorize("hasAnyAuthority('sys:user:role')")
    @Transactional
    @PostMapping("/role/{userId}")
    public Result rolePerm(@PathVariable Long userId,@RequestBody Long [] roleIds){
        List<SysUserRole> sysUserRoleList=new ArrayList<>();
        Arrays.stream(roleIds).forEach(r ->{
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);
            sysUserRoleList.add(sysUserRole);
        });
//        删除原来的旧角色
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",userId));
//        添加新角色
        boolean b = sysUserRoleService.saveBatch(sysUserRoleList);
//        删除缓存
        SysUser sysUser = sysUserService.getById(userId);
        sysUserService.clearAuthorityInfoByUserName(sysUser.getUsername());
        return Result.success(b);
    }

    @PostMapping("/repass")
    @PreAuthorize("hasAnyAuthority('sys:user:repass')")
    public Result rePassword(@RequestBody Long userId,Principal principal){
        SysUser sysUser=sysUserService.getById(userId);
        boolean equals = principal.getName().equals(sysUser.getUsername());
        Assert.isTrue(!equals,"只能在个人中心内修改自己的信息!");
        String password = bCryptPasswordEncoder.encode(Const.DEFAULT_PASSWORD);
        sysUser.setPassword(password);
        sysUser.setUpdated(LocalDateTime.now());
        boolean b = sysUserService.updateById(sysUser);
        return Result.success(b);
    }
    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PasswordDto passwordDto, Principal principal){
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        boolean matches = bCryptPasswordEncoder.matches(passwordDto.getOldPassword(), sysUser.getPassword());
        Assert.isTrue(matches,"旧密码不正确");
        sysUser.setPassword(bCryptPasswordEncoder.encode(passwordDto.getNewPassword()));
        sysUser.setUpdated(LocalDateTime.now());
        boolean b = sysUserService.updateById(sysUser);
        return Result.success(b);
    }
}
